//
//  ShopManageViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/9.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ShopManageViewController.h"

#import "SetTimeViewController.h"
#import "ShopSetViewController.h"
#import "ShopAdornViewController.h"
#import "PublushGoodsViewController.h"
#import "ShopGoodsDetailVC.h"
#import "ShopGoodsTableViewCell.h"
#import "ShopInfo.h"

@interface ShopManageViewController ()<UITableViewDelegate, UITableViewDataSource>{
    UIView *operateView;
    UIButton *adornBtn;
    UIButton *publishBtn;
}

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) UIView      * moveLine;
@property (nonatomic, strong) UIButton    * selectBtn;
@property (nonatomic, strong) ShopInfo    * shopInfo;
@property (nonatomic, strong) UIImageView * headBg;
@property (nonatomic, strong) UIImageView * headImage;
@property (nonatomic, strong) UILabel     * nameLabel;
@property (nonatomic, strong) UILabel     * detailLabel;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *pageArray;
@property (nonatomic, strong) NSMutableArray *currentPageArray;
@property (nonatomic, assign) NSInteger saleStatu;

@end

@implementation ShopManageViewController

-(void)setShopInfo:(ShopInfo *)shopInfo
{
    _shopInfo = shopInfo;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"店铺管理";
    self.dataArray = [NSMutableArray array];
    self.pageArray = [NSMutableArray array];
    self.currentPageArray = [NSMutableArray array];
    for (int i = 0; i < 4; i++) {
        [self.dataArray addObject:[NSMutableArray array]];
        [self.currentPageArray addObject:@"1"];
        [self.pageArray addObject:@"1"];
    }
    self.saleStatu = 0;
    
    UIButton *setBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [setBtn setImage:[UIImage imageNamed:@"店铺管理-设置"] forState:UIControlStateNormal];
    setBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 25, 0, 0);
    [setBtn addTarget:self action:@selector(setClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:setBtn];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, -STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT + STATUS_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(101);
    [self.view addSubview:self.tableView];
    
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    
    [self getData];
    [self setBottom];
    [kNotificationCenter addObserver:self selector:@selector(getData) name:@"ReloadShop" object:nil];
}

- (void)dealloc {
    [kNotificationCenter removeObserver:self name:@"ReloadShop" object:nil];
}

- (void)setClick {
    SetTimeViewController *vc = [[SetTimeViewController alloc] init];
    vc.shopInfo = _shopInfo;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getData {
    NSString *url = [NSString stringWithFormat:@"%@app/shop_info",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken]};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSError *error = nil;
            self.shopInfo = [[ShopInfo alloc] initWithDictionary:successResponse[@"data"] error:&error];
            [self setHead];
            [self getGoodsData];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)headerRefresh {
    [self.currentPageArray setObject:@"1" atIndexedSubscript:_saleStatu];
    [self getGoodsData];
    [self.tableView.mj_header endRefreshing];
}

- (void)footerRefresh {
    if ([self.currentPageArray[_saleStatu] integerValue] < [self.pageArray[_saleStatu] integerValue]) {
        NSInteger currentPage = [self.currentPageArray[_saleStatu] integerValue];
        currentPage++;
        [self.currentPageArray setObject:[NSString stringWithFormat:@"%ld",(long)currentPage] atIndexedSubscript:_saleStatu];
        [self getGoodsData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)getGoodsData {
    NSString *isSale = @"";
    switch (_saleStatu) {
        case 0:
            isSale = @"1";
            break;
        case 1:
            isSale = @"-1";
            break;
        case 2:
            isSale = @"-2";
            break;
        case 3:
            isSale = @"0";
            break;
        default:
            break;
    }
    NSString *url = [NSString stringWithFormat:@"%@app/shop_product",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"shop_id":_shopInfo.Id,@"is_sale":isSale,@"page":self.currentPageArray[_saleStatu]};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            if ([self.currentPageArray[self.saleStatu] integerValue] == 1) {
                [self.dataArray[self.saleStatu] removeAllObjects];
            }
            [self.pageArray setObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"last_page"]] atIndexedSubscript:self.saleStatu];
            NSError *error = nil;
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                ShopGoodsListModel *model = [[ShopGoodsListModel alloc] initWithDictionary:dic error:&error];
                model.statu = [NSString stringWithFormat:@"%ld",(long)self.saleStatu];
                [self.dataArray[self.saleStatu] addObject:model];
            }
            [self.tableView reloadData];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)setHead {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(192) + STATUS_BAR_HEIGHT)];
    self.tableView.tableHeaderView = headView;
    
    self.headBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(192) + STATUS_BAR_HEIGHT)];
    self.headBg.image = [UIImage imageNamed:@"头部背景"];
    [headView addSubview:self.headBg];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:backBtn];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(60), STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(120), 44)];
    titleLabel.text = @"店铺管理";
    titleLabel.font = Kfont(16);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:titleLabel];
    
    UIButton *setBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH -  44, STATUS_BAR_HEIGHT,  44, 44)];
    [setBtn setImage:[UIImage imageNamed:@"店铺管理-设置"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(setClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:setBtn];
    
    self.headImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(54) + STATUS_BAR_HEIGHT, ScreenX375(72), ScreenX375(72))];
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:_shopInfo.logo] placeholderImage:nil options:SDWebImageRetryFailed];
    self.headImage.layer.cornerRadius = ScreenX375(5);
    self.headImage.clipsToBounds = YES;
    [headView addSubview:self.headImage];
    
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(95), ScreenX375(52) + STATUS_BAR_HEIGHT, ScreenX375(200), ScreenX375(17))];
    self.nameLabel.text = _shopInfo.name;
    self.nameLabel.textColor = [UIColor whiteColor];
    self.nameLabel.font = Kfont(14);
    [headView addSubview:self.nameLabel];
    
    self.detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(95), ScreenX375(73) + STATUS_BAR_HEIGHT, ScreenX375(200), ScreenX375(17))];
    self.detailLabel.text = _shopInfo.intro;
    self.detailLabel.textColor = [UIColor whiteColor];
    self.detailLabel.font = Kfont(12);
    [headView addSubview:self.detailLabel];
    
    CGFloat width = ScreenX375(95);
    NSArray *arr = _shopInfo.labels;
    for (int i = 0; i < arr.count; i++) {
        CGFloat textWidth = kGetStringWidth(arr[i][@"name"], CGSizeMake(MAXFLOAT, ScreenX375(17)), Kfont(10)) + ScreenX375(12);
        UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(width, ScreenX375(97) + STATUS_BAR_HEIGHT, textWidth, ScreenX375(17))];
        tagLabel.text = arr[i][@"name"];
        tagLabel.textColor = [UIColor whiteColor];
        tagLabel.backgroundColor = ThemeColor;
        tagLabel.textAlignment = NSTextAlignmentCenter;
        tagLabel.layer.cornerRadius = ScreenX375(7.5);
        tagLabel.clipsToBounds = YES;
        tagLabel.font = Kfont(10);
        [headView addSubview:tagLabel];
        
        width = width + ScreenX375(5) + textWidth;
    }
    
    UIButton *detailBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 44, STATUS_BAR_HEIGHT + ScreenX375(60), 44, 44)];
    [detailBtn setImage:[UIImage imageNamed:@"更多白色"] forState:UIControlStateNormal];
    [headView addSubview:detailBtn];
    
    UIButton *shopSetClick = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(95), ScreenX375(52) + STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(95), ScreenX375(80))];
    [shopSetClick addTarget:self action:@selector(shopSetClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:shopSetClick];
    
    UIView *numView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(141) + STATUS_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(51))];
    numView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [headView addSubview:numView];
    
    NSArray *noteArr = @[@"收藏",@"成交",@"好评",@"好评率"];
    NSArray *numArr = @[@"0人",@"0件",@"0笔",@"100%"];
    CGFloat classWidth = SCREEN_WIDTH / 4;
    for (int i = 0; i < noteArr.count; i++) {
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * classWidth, ScreenX375(28), classWidth, ScreenX375(14))];
        noteLabel.text = noteArr[i];
        noteLabel.textColor = [UIColor whiteColor];
        noteLabel.textAlignment = NSTextAlignmentCenter;
        noteLabel.font = Kfont(12);
        [numView addSubview:noteLabel];
        
        UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * classWidth, ScreenX375(7), classWidth, ScreenX375(16))];
        numLabel.text = numArr[i];
        numLabel.textColor = [UIColor whiteColor];
        numLabel.textAlignment = NSTextAlignmentCenter;
        numLabel.font = Kfont(14);
        [numView addSubview:numLabel];
        
        if (i != 0) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(i * classWidth, ScreenX375(6), 1, ScreenX375(39))];
            line.backgroundColor = [UIColor whiteColor];
            [numView addSubview:line];
        }
    }
}

- (void)shopSetClick {
    ShopSetViewController *vc = [[ShopSetViewController alloc] init];
    vc.shopInfo = _shopInfo;
    vc.shopInfoId = _shopInfo.Id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setBottom {
    adornBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(49), SCREEN_WIDTH / 2, ScreenX375(49))];
    [adornBtn setTitle:@"店铺装修" forState:UIControlStateNormal];
    [adornBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    adornBtn.titleLabel.font = Kfont(16);
    adornBtn.backgroundColor = REXADECIMALCOLOR(@"#ff9500");
    [adornBtn addTarget:self action:@selector(turnToAdorn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:adornBtn];
    
    publishBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - ScreenX375(49), SCREEN_WIDTH / 2, ScreenX375(49))];
    [publishBtn setTitle:@"发布商品" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    publishBtn.titleLabel.font = Kfont(16);
    publishBtn.backgroundColor = ThemeColor;
    [publishBtn addTarget:self action:@selector(turnToPublish) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:publishBtn];
}

- (void)turnToAdorn {
    ShopAdornViewController *vc = [[ShopAdornViewController alloc] init];
    vc.isMine = YES;
    vc.shop_id = _shopInfo.Id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)turnToPublish {
    PublushGoodsViewController *vc = [[PublushGoodsViewController alloc] init];
    vc.shopId = _shopInfo.Id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArray[_saleStatu] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopGoodsTableViewCell *cell = [ShopGoodsTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.shopGoodsListModel = self.dataArray[_saleStatu][indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return ScreenX375(51);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(51))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    
    if (!operateView) {
        operateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(41))];
        operateView.backgroundColor = [UIColor whiteColor];
        
        NSArray *nameArr = @[@"出售中",@"审核中",@"不通过",@"已下架"];
        for (int i = 0; i < nameArr.count; i++) {
            UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 4, 0, SCREEN_WIDTH / 4, ScreenX375(41))];
            [typeBtn setTitle:nameArr[i] forState:UIControlStateNormal];
            [typeBtn setTitleColor:ThemeColor forState:UIControlStateSelected];
            [typeBtn setTitleColor:REXADECIMALCOLOR(@"#999999") forState:UIControlStateNormal];
            typeBtn.titleLabel.font = Kfont(14);
            typeBtn.tag = 100 + i;
            if (i == 0) {
                typeBtn.selected = YES;
                _selectBtn = typeBtn;
            }
            [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
            [operateView addSubview:typeBtn];
        }
        
        self.moveLine = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 4 - ScreenX375(30)) / 2, ScreenX375(41) - 2, ScreenX375(30), 2)];
        self.moveLine.backgroundColor = ThemeColor;
        [operateView addSubview:self.moveLine];
    }
    [view addSubview:operateView];
    
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    ShopGoodsListModel *model = self.dataArray[_saleStatu][indexPath.row];
    ShopGoodsDetailVC *goodsDetailVC = [[ShopGoodsDetailVC alloc] init];
    //将商品ID传入下个界面
    goodsDetailVC.goods_id = model.Id;
    goodsDetailVC.statu = model.statu;
    [self.navigationController pushViewController:goodsDetailVC animated:true];
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _saleStatu = button.tag - 100;
    if ([self.dataArray[_saleStatu] count] == 0) {
        [self getGoodsData];
    }else {
        [self.tableView reloadData];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 4 - ScreenX375(30)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 4, ScreenX375(41) - 2, ScreenX375(30), 2);
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _tableView && scrollView.contentOffset.y > 0) {
        if (scrollView.contentOffset.y > ScreenX375(192) - 21 * SCREEN_WIDTH / 375) {
            self.navigationController.navigationBarHidden = NO;
            _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49));
            adornBtn.frame = CGRectMake(0, SCREEN_HEIGHT - ScreenX375(49) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH / 2, ScreenX375(49));
            publishBtn.frame = CGRectMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - ScreenX375(49) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH / 2, ScreenX375(49));
        }else {
            self.navigationController.navigationBarHidden = YES;
            _tableView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT + STATUS_BAR_HEIGHT - ScreenX375(49));
            adornBtn.frame = CGRectMake(0, SCREEN_HEIGHT - ScreenX375(49), SCREEN_WIDTH / 2, ScreenX375(49));
            publishBtn.frame = CGRectMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - ScreenX375(49), SCREEN_WIDTH / 2, ScreenX375(49));
        }
    }
}

@end
